package cc.messcat.web.fupin;

import cc.messcat.common.constant.CommonConstant;
import cc.messcat.common.constant.CommonRedisConstant;
import cc.messcat.common.model.FilesUploadModel;
import cc.messcat.common.model.Pager;
import cc.messcat.common.model.ResponseBean;
import cc.messcat.common.util.BeanUtil;
import cc.messcat.common.util.LogUtil;
import cc.messcat.common.util.StringUtil;
import cc.messcat.entity.area.Area;
import cc.messcat.entity.fupin.*;
import cc.messcat.entity.helpPerson.HelpPerson;
import cc.messcat.entity.system.*;
import cc.messcat.entity.vo.CompanyVo;
import cc.messcat.log.OperationLog;
import cc.messcat.service.area.AreaService;
import cc.messcat.service.fupin.*;
import cc.messcat.service.helppeson.HelppesonService;
import cc.messcat.service.helpunits.HelpunitsService;
import cc.messcat.service.system.PermissionService;
import cc.messcat.service.system.UserService;
import cc.messcat.util.Collections;
import cc.messcat.util.ImageHelper;
import cc.messcat.util.QRCodeUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/company")
public class CompanyController {
    private static Logger log = LoggerFactory.getLogger(CompanyController.class);

    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private PermissionService permissionService;
    
    @Autowired
    public UserService userService;
    
    
    @Value("#{ configProperties['web.name'] }")
	private String projectName;

	@Value("#{ configProperties['upload.companyLegalPersonPic.path'] }")
	private String imageFolderName;
	
	@Value("#{ configProperties['upload.file.maxUploadSize'] }")
	private Long fileMaxSize;

    /**
     * 企业列表查询
     *
     * @throws Exception
     */
//	@OperationLog(desc = "企业列表查询", module = "企业管理")
    @RequestMapping("/queryCompanyList") 
    @ResponseBody
    @SuppressWarnings("all")
    public Object queryPoorFamily(Integer pageNo, Integer pageSize,String company_name,String legal_person,
                                  String cry,String village, HttpServletRequest request, HttpSession session) throws Exception {
        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 10;
        }
        // 兼容操作
     /*   if (BeanUtil.isValid(cty))
            poorFamily.setCounty(cty);
        if (BeanUtil.isValid(cry))
            poorFamily.setCountry(cry);*/

        //页面按钮授权
       McUser user = (McUser) request.getSession().getAttribute("user");
        Permission poorFamilyManagementPermission = permissionService.getPermissionByURI("povertyStrickenMng");
        List<String> buttonPermissionList = new ArrayList<>();
        for (Role e : userService.retrieveObject(user.getId()).getRoles()) {
            for (Permission p : e.getPermissions()) {
                if (p.getPermissionId() == poorFamilyManagementPermission.getId() && p.getName().contains("button-"))
                    buttonPermissionList.add(p.getName());
            }
        }
       
        Pager pager = this.companyService.getCompanyPager(pageNo, pageSize, company_name, legal_person, cry, village, "",
                user);
        
        Map result = Collections.generateHashMap(new Object[]{"pageCount", "pageNo", "pageSize", "pageSizeList", "rowCount", "resultList", "buttonPermissionList"},
                new Object[]{pager.getPageCount(), pager.getPageNo(), pager.getPageSize(), pager.getPageSizeList(), pager.getRowCount(), pager.getResultList(), buttonPermissionList});
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, result);
   }
    
    /**
     * 根据企业id查询企业及对应贫困户成员信息(分页)
     */
    @RequestMapping("/queryCompanyFamilyById")
    @ResponseBody
    public Object queryFamily(String id,Integer pageNo, Integer pageSize) {
    	
    	if(null==id||"".equals(id)){
    		return new ResponseBean(CommonConstant.EXCEPTION_CODE_500,"操作失败,企业id不能为空!");
    	}
    	
    	  if (pageNo == null || pageNo < 1) {
              pageNo = 1;
          }
          if (pageSize == null || pageSize < 1) {
              pageSize = 10;
          }
          
          
    	
           Pager<CompanyVo> pager = this.companyService.queryCompanyFamilyById(id,pageNo,pageSize);
           
           Map result = Collections.generateHashMap(new Object[]{"pageCount", "pageNo", "pageSize", "pageSizeList", "rowCount", "resultList"},
                   new Object[]{pager.getPageCount(), pager.getPageNo(), pager.getPageSize(), pager.getPageSizeList(), pager.getRowCount(), pager.getResultList()});
        
        return  new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, result);
    }
    
    
    /**
     * 根据企业id查询企业
     */
    @RequestMapping("/queryCompanyById")
    @ResponseBody
    public Object queryFamily(String id) {
    	
    	if(null==id||"".equals(id)){
    		return new ResponseBean(CommonConstant.EXCEPTION_CODE_500,CommonConstant.company_id_canntNull);
    	}
    	
         Company company =  this.companyService.queryCompanyById(id);
           
          
        return  new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_FIND_SUCCESS, company);
    }
    
    
    
    /**
     * 根据企业id删除企业信息
     */
    @RequestMapping("/delCompanyById")
    @ResponseBody
    public Object editCompanyById(String id) {
    	
    	if(null==id||"".equals(id)){
    		return new ResponseBean(CommonConstant.EXCEPTION_CODE_500,CommonConstant.company_id_canntNull);
    	}
    	
    	try {
    		this.companyService.delCompanyById(id);
		} catch (Exception e) {
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_DELETE_FAIL);
		}
    		 
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_DELETE_SUCCESS);
    }
    
    /**
     *新增企业信息
     * @throws Exception 
     */
    @RequestMapping("/addCompany")
    @ResponseBody
    public Object addCompany( HttpServletRequest request,Company company,MultipartFile file ) throws Exception {
    	
    	String fileUri="";
    	if (!file.isEmpty()) {
			FilesUploadModel fileModel = new FilesUploadModel(file.getOriginalFilename(), file.getInputStream(),
					projectName, imageFolderName);
			fileModel.writeFileByBinary();
			if (!fileModel.isFileExists()) {
				throw new Exception("文件写入异常！！");
			}
			fileUri= fileModel.getFileUri();
		}
    	
    	 McUser user = (McUser) request.getSession().getAttribute("user");
    	 company.setCreate_person(user.getName());
    	 company.setIs_del("0");
 		 company.setCreate_time(new  Date());
 		 if(!"".equals(fileUri)){
 			 company.setLegal_person_pic(fileUri);
 		 }
 		 
    	try {
    		this.companyService.addCompany(company);
		} catch (Exception e) {
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_ADD_FAIL);
		}
    		 
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_ADD_SUCCESS);
    }
    
    
    /**
     *修改企业信息
     * @throws Exception 
     */
    @RequestMapping("/editCompany")
    @ResponseBody
    public Object editCompany( HttpServletRequest request,Company company,MultipartFile file ) throws Exception {
    	
    	String fileUri="";
    	if (!file.isEmpty()) {
			FilesUploadModel fileModel = new FilesUploadModel(file.getOriginalFilename(), file.getInputStream(),
					projectName, imageFolderName);
			fileModel.writeFileByBinary();
			if (!fileModel.isFileExists()) {
				throw new Exception("文件写入异常！！");
			}
			fileUri= fileModel.getFileUri();
		}
    	
    	if(!"".equals(fileUri)){
			 company.setLegal_person_pic(fileUri);
		 }
    	 
    	try {
    		 
    		
    		this.companyService.updateCompany(company);
		} catch (Exception e) {
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.MSG_UPDATE_FAIL);
		}
    		 
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_UPDATE_SUCCESS);
    }
    
    /**
     *校验企业名称是否唯一
     * @throws UnsupportedEncodingException 
     */
    @RequestMapping("/checkCompanyName")
    @ResponseBody
    public Object checkCompanyName(String company_name) throws UnsupportedEncodingException {
    	
    	
    	
    	int  count = this.companyService.checkCompanyName(company_name);
		if(count>=1){
			return new ResponseBean(CommonConstant.EXCEPTION_CODE_500, CommonConstant.company_name_existed);
		}
    		 
        return new ResponseBean(CommonConstant.SUCCESS_CODE_200, CommonConstant.MSG_SUCCESS);
    }
    
    
    
    

    
   
}
